//
//  PRMainViewCtr.m
//  PearRich
//
//  Created by 谢黎鹏 on 2020/1/11.
//  Copyright © 2020年 谢黎鹏. All rights reserved.
//

#import "PRMainViewCtr.h"
#import "PRMainViewCell.h"
#import "PRAddNewRecordVC.h"
#import "ChartDataVC.h"
#import "PRInnerPayHandle.h"
#import <PGDatePicker/PGDatePickManager.h>
@interface PRMainViewCtr ()<UITableViewDataSource,UITableViewDelegate,PGDatePickerDelegate>
@property(nonatomic,retain)UITableView * myTab;
@property(nonatomic,retain)QMUIButton * titleBtn;
@property(nonatomic,retain)NSMutableArray * dataArr;
@property(nonatomic,assign)NSInteger page;
@property(nonatomic,retain)NSDate * selDate;
@property(nonatomic,retain)PRInnerPayHandle * iapHandle;
@end

@implementation PRMainViewCtr
- (void)viewDidLoad{
    [super viewDidLoad];
    self.rightBtnImage = Image(@"banyuanhuan");
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(mainViewReload) name:@"mainviewreload" object:nil];
    self.iapHandle = [[PRInnerPayHandle alloc]init];
    self.dataArr = [NSMutableArray new];
    self.selDate = [NSDate date];
    [self configDateTitle:self.selDate];
    [self createUI];
    [self getData];
    
}
- (void)rightBtnClick{    
    [self.navigationController pushViewController:[ChartDataVC new] animated:YES];
}
-(void)mainViewReload{
    [self.myTab.mj_header beginRefreshing];
}
-(void)getData{
    if (_dataArr.count>0) {
        [_dataArr removeAllObjects];
    }
    [QMUITips showLoadingInView:self.view];
    NSArray * arr =  [PRMainViewModel bg_find:GoodsInfoTab type:bg_createTime dateTime:[NSString stringWithFormat:@"%ld-%02ld",self.selDate.year,self.selDate.month]];
    NSArray * arrm = [[arr reverseObjectEnumerator] allObjects];
    for (int i =0;i<arrm.count;i++) {
        PRMainViewModel * mo = arrm[i];
        NSString * day = [mo.createTime substringWithRange:NSMakeRange(8, 2)];
        NSMutableArray * dayArr = [NSMutableArray new];
        [dayArr addObject:mo];
        for (int j =i+1; j<arrm.count; j++) {
            PRMainViewModel * mj = arrm[j];
            NSString * dj = [mj.createTime substringWithRange:NSMakeRange(8, 2)];
            if ([day isEqualToString:dj]) {
                [dayArr addObject:mj];
            }else{
                [self.dataArr addObject:dayArr];
                break;
            }
            i = j;
        }
        if (![self.dataArr containsObject:dayArr]) {
            [self.dataArr addObject:dayArr];
        }
    }
    
    [self.myTab.mj_header endRefreshing];
    [self.myTab reloadData];
    [Mytools NeedResetNoViewWithTable:self.myTab andArr:self.dataArr];
    [QMUITips hideAllTips];
}
-(void)configDateTitle:(NSDate*)date{
    NSString * dateStr = [NSString stringWithFormat:@"%ld月",date.month];
    self.titleBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [self.titleBtn setTitle:dateStr forState:UIControlStateNormal];
    [self.titleBtn setImagePosition:QMUIButtonImagePositionRight];
    self.titleBtn.spacingBetweenImageAndTitle = 10;
    [self.titleBtn addTarget:self action:@selector(choseDateClick) forControlEvents:UIControlEventTouchUpInside];
    [self.titleBtn setImage:Image(@"fold_down") forState:UIControlStateNormal];
    self.titleBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.titleBtn setTitleColor:[UIColor normalColor:UIColorBlack darkColor:UIColorWhite] forState:UIControlStateNormal];
    [self.navView addSubview:self.titleBtn];
    self.titleBtn.sd_layout.centerXEqualToView(self.navView).topSpaceToView(self.navView, kStatusBarHeight).widthIs(120).heightIs(kNavBarHeight);
}
-(void)choseDateClick{
    PGDatePickManager *datePickManager = [[PGDatePickManager alloc]init];
    datePickManager.headerViewBackgroundColor = [UIColor whiteColor];
    datePickManager.isShadeBackground = true;
    datePickManager.confirmButtonTextColor = ThemeColor;
    
    PGDatePicker *datePicker = datePickManager.datePicker;
    datePicker.isHiddenMiddleText = false;
    datePicker.delegate = self;
    datePicker.textColorOfSelectedRow = [UIColor blackColor];
    datePicker.textColorOfOtherRow = [UIColor colorWithHue:0 saturation:0 brightness:0.36 alpha:1];
    datePicker.lineBackgroundColor = [UIColor colorWithHue:0 saturation:0 brightness:0.36 alpha:1];
    datePicker.datePickerMode = PGDatePickerModeYearAndMonth;
    datePicker.maximumDate = [NSDate date];
    [self presentViewController:datePickManager animated:NO completion:nil];
}
#pragma PGDatePickerDelegate
- (void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents  {
    /*dateComponents格式：Calendar Year: 2018  Month: 1  Leap month: no  Day: 26  Hour: 8  Minute: 49  Second: 32  Weekday: 3*/
    [self.titleBtn setTitle:[NSString stringWithFormat:@"%ld月",dateComponents.month] forState:UIControlStateNormal];
    NSString * str = [NSString stringWithFormat:@"%ld-%02ld-01 00:00:00",dateComponents.year,dateComponents.month];
    self.selDate = [Mytools dateStrToDate:str];
    [self.dataArr removeAllObjects];
    [self.myTab.mj_header beginRefreshing];
}
-(void)createUI{
    self.myTab = [[UITableView alloc]initWithFrame:Frame(0, kTopHeight, IPHONE_WIDTH, IPHONE_HEIGHT-kTopHeight-kTabbarHeight) style:UITableViewStyleGrouped];
    _myTab.delegate = self;
    _myTab.estimatedRowHeight = 100;
    _myTab.dataSource = self;
    _myTab.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getData];
    }];
    _myTab.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_myTab registerNib:[UINib nibWithNibName:@"PRMainViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:self.myTab];
    
    UIButton * addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.titleLabel.font = [UIFont systemFontOfSize:24];
    [addBtn setImage:Image(@"add_picker") forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addBtn];
    addBtn.sd_cornerRadiusFromHeightRatio = @(0.5);
    addBtn.sd_layout.centerXEqualToView(self.view).bottomSpaceToView(self.view, kTabbarHeight+30).widthIs(45).heightEqualToWidth();
}
-(void)addBtnClick{
    PRAddNewRecordVC * vc = [PRAddNewRecordVC new];
    vc.saveBlock = ^{
        [self.myTab.mj_header beginRefreshing];
    };
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark tableView代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArr.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSMutableArray * arr = self.dataArr[section];
    return arr.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PRMainViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    NSMutableArray * arr = self.dataArr[indexPath.section];
    cell.model = arr[indexPath.row];
    if (indexPath.row == arr.count-1) {
        cell.isLastRow = YES;
    }else{
        cell.isLastRow = NO;
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 55;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 5;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * header = [UIView new];
    UIView * bgView = [UIView new];
    bgView.backgroundColor = [UIColor normalColor:UIColorWhite darkColor:[UIColor darkGrayColor]];
    bgView.frame = Frame(10, 10, IPHONE_WIDTH-20, 45);
    [header addSubview:bgView];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:Frame(0, 0, IPHONE_WIDTH-20, 45) byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(5, 5)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = bgView.bounds;
    maskLayer.path = maskPath.CGPath;
    bgView.layer.mask = maskLayer;
    PRMainViewModel * mo = self.dataArr[section][0];
    UILabel * lab = [UILabel labelWithTitle:[mo.createTime substringWithRange:NSMakeRange(0, 11)] color:[UIColor normalColor:UIColorBlack darkColor:UIColorWhite] fontSize:14];
    [bgView addSubview:lab];
    lab.sd_layout.leftSpaceToView(bgView, 10).centerYEqualToView(bgView).heightIs(14);
    [lab setSingleLineAutoResizeWithMaxWidth:300];
    UIView * line = [UIView new];
    line.backgroundColor = [UIColor normalColor:LineColor darkColor:[UIColor lightGrayColor]];
    line.frame = Frame(10, 54.5, IPHONE_WIDTH-20, 0.5);
    [header addSubview:line];
    return  header;
}
-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView * footer = [UIView new];
    UIView * bgView = [UIView new];
    bgView.backgroundColor = [UIColor normalColor:UIColorWhite darkColor:[UIColor darkGrayColor]];
    bgView.frame = Frame(10, 0, IPHONE_WIDTH-20, 5);
    [footer addSubview:bgView];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:Frame(0, 0, IPHONE_WIDTH-20, 5) byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(5, 5)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = bgView.bounds;
    maskLayer.path = maskPath.CGPath;
    bgView.layer.mask = maskLayer;
    return  footer;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    PRMainViewModel * mo = self.dataArr[indexPath.section][indexPath.row];
    PRAddNewRecordVC * vc = [PRAddNewRecordVC new];
    vc.editModel = mo;
    vc.saveBlock = ^{
        [self.myTab.mj_header beginRefreshing];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

@end
